

# SECe7ad2ec0c1af0996e4571ec63de83c4af5394ce597a4b78641447a60e631a2c1
# https://oapi.dingtalk.com/robot/send?access_token=994f961ef061d7e9b9f7e478ca8052d2e7b7e598c551ae9e5590b43ab7385db5

import time
import hmac
import hashlib
import base64
import urllib.parse
import json


secret = 'SECe7ad2ec0c1af0996e4571ec63de83c4af5394ce597a4b78641447a60e631a2c1'
url='https://oapi.dingtalk.com/robot/send?access_token=994f961ef061d7e9b9f7e478ca8052d2e7b7e598c551ae9e5590b43ab7385db5'
headers = {"Content-Type": "application/json"}


def sendDingDing(data_txt):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    print(timestamp)
    print(sign)
    data = {
        "msgtype": "text",
        "text": {
            "content": data_txt  # 抓取数据发送的内容放到alldata
        },
        "at": {
            "isAtAll": True  # @全体成员（在此可设置@特定某人）
        }
    }
    # 对请求的数据进行json封装
    sendData = json.dumps(data)
    sendData = sendData.encode("utf-8")
    # 发送请求
    request = urllib.request.Request(url=url + '&timestamp=' + timestamp + '&sign=' + sign, data=sendData,
                                     headers=headers)
    # 将请求发回的数据构建成为文件格式
    opener = urllib.request.urlopen(request)